<?php

namespace App\Api\Controllers;

/* use App\Http\Controllers\Controller; */
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use App\Helper\Utils\TimeUtil;
use App\Api\Services\ReceiptService;
use App\Api\Models\ReceiptModel;
use App\Http\Controllers\Api\BaseController;
use App\Api\Models\DeliveryGoodsModel;
class ReceiptController extends BaseController
{
    /**
     * 添加收据
     */
    public function add(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'accountant'     =>'string',//会计
            'teller'         =>'string',//出纳
            'handling_person'=>'string',//经手人           
            'date_recorded'  =>'string',//入账时间 
            'receive'        =>'string',//收到
            'amount_in_words'=>'string',//大写金额
            'remark'         =>'string',//备注
            'money'          =>'numeric|min:0',//金额
           
        ],[
            'money.numeric'   => '金额只能为数字',
            'money.min'       => '金额最小只能为0',           
    
        ]);
    
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
    
        if(!empty($unit_stamp_files = $request->file('unit_stamp'))){
    
            if($unit_stamp_files->isValid()){
                 
                $img_path = $unit_stamp_files->store('yz/imgs/'.date('Y').'-'.date('m').'-'.date('d'));
                 
                $data['unit_stamp'] = '/uploads/'.$img_path;
            }else{
                return response()->json(['code' => 1,'msg' => '单位印章，添加失败！','data' => '']);
            }             
        }
        //开启事务
       DB::beginTransaction();       
        try{
            //收据
            $dData = $data;
            $dData['created_at']   = time();
            $dData['user_id']      = $this->getUserId();
            $dData['main_id']      = $this->getMainUserId(); 
            
            if(empty($dData['receipt_no'])){
                
                $dData['receipt_no']  = 'NO.'. $this->getMainUserId().TimeUtil::getMillisecond();//收据号
            
            }
            
            ReceiptService::add($dData);
            
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加收据');
        }
         
    }
    
    /**
     * 删除收据信息
     * @param ids (删除多个逗号分隔)
     */
    public function delete(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'ids'       =>'required',//收据id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
        
        $id_data = [];
        $id_arr  = explode(',',$data['ids']);
        
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
    
        //$info = ReceiptService::getReceiptInfo($condition);
        $list = ReceiptModel::select('id')->where($condition)->whereIn('id',$id_arr)->get()->toArray();
        
        if(!empty($list)){
            
            foreach ($list as $k=>$v){
                
                $id_data[]=$v['id'];
            }
            
            $bool = ReceiptModel::where($condition)->whereIn('id',$id_data)->delete();;
             
            if($bool){
                
                return $this->success();
                 
            }else{
                return $this->fail('','删除失败');
            }
        }
        return $this->fail('','收据，不存在！');
    }
    
    /**
     * 修改收据
     *
     */
    public function update(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'receipt_id'     =>'required|integer',//收据id
            'accountant'     =>'string',//会计
            'teller'         =>'string',//出纳
            'handling_person'=>'string',//经手人           
            'date_recorded'  =>'string',//入账时间 
            'receive'        =>'string',//收到
            'amount_in_words'=>'string',//大写金额
            'remark'         =>'string',//备注           
            'money'          =>'numeric|min:0',//金额
           
        ],[
            'money.numeric'   => '金额只能为数字',
            'money.min'       => '金额最小只能为0',           
    
        ]);
    
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        
        if(!empty($unit_stamp_files = $request->file('unit_stamp'))){
        
            if($unit_stamp_files->isValid()){
                 
                $img_path = $unit_stamp_files->store('yz/imgs/'.date('Y').'-'.date('m').'-'.date('d'));
                 
                $data['unit_stamp'] = '/uploads/'.$img_path;
            }else{
                return response()->json(['code' => 1,'msg' => '单位印章，修改失败！','data' => '']);
            }   
        }
        
        $info = ReceiptService::getReceiptInfo(['id'=> $data['receipt_id']]);
         
        if(empty($info)){
             
            return $this->fail('','收据号,不存在！');
        }
        //开启事务
        DB::beginTransaction();
        try{
            //收据
            $updData = $data;
            
            $condition['user_id'] = $this->getUserId();
            $condition['main_id'] = $this->getMainUserId();
            $condition['id']      = $updData['receipt_id'];
            
            unset($updData['receipt_id']);
            $updData['updated_at'] = time();
            
            ReceiptService::update($condition,$updData);
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'修改收据');
        }
    
    }
    
    /**
     * 收据信息
     * @param receipt_id
     */
    public function find(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'receipt_id'       =>'required|integer',//收据id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
    
        $condition['id']      = $data['receipt_id'];
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
    
        $info = ReceiptService::getReceiptInfo($condition);
           
        return $this->success($info);
    }
    
    /**
     * 收据列表
     */
    public function ReceiptList(Request $request){    
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        
        $id_arr = [];
        $receipt_id_arr = [];
    
        $keyword = empty($data['keyword'])?'':$data['keyword'];
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
        if(!empty($keyword)){
    
            $list = ReceiptModel::select('id')->where($condition)
            ->where(function($query) use ($keyword) {
                $query->orWhere('receipt_no', 'like', '%'.$keyword.'%');
                $query->orWhere('accountant', 'like', '%'.$keyword.'%');
                $query->orWhere('teller', 'like', '%'.$keyword.'%');
                $query->orWhere('handling_person', 'like', '%'.$keyword.'%');
            })->orderBy('id','desc')
            ->get()->toArray();
           
            if(!empty($list)){
    
                foreach ($list as $k=>$v){
    
                    $id_arr[$k] = $v['id'];
                }
            }
    
            $receipt_id_arr = array_unique($id_arr);
            
            if(empty($receipt_id_arr)){
            
                $receipt_id_arr[0] ="0";
            }
        }
    
        $list = ReceiptService::getList($condition,$receipt_id_arr,$data['pageSize'],$data['currentPage']);
    
       
        return $this->success($list);
    
    }
   
}
